package org.boot.thread.atomic;

import lombok.Data;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 账户实体类-非安全的
 *
 * @author 李坤
 * @date 2022/8/26 15:03
 */
@Data
public class Account implements Serializable {

    /**
     * 账户ID
     */
    private String id;

    /**
     * 账户余额
     */
    private BigDecimal balance;

    /**
     * 账户余额的原子引用
     */
    private AtomicReference<BigDecimal> balanceReference;

    /**
     * 默认的构造函数
     *
     * @param id      账户ID
     * @param balance 账户余额
     */
    public Account(String id, BigDecimal balance) {
        this.id = id;
        this.balance = balance;
        this.balanceReference = new AtomicReference<>(this.balance);
    }

    /**
     * 线程安全的变更账户余额
     *
     * @param amount 变更金额
     *
     * @return 变更后余额
     */
    public BigDecimal safeTrade(BigDecimal amount) {
        return balanceReference.accumulateAndGet(amount, BigDecimal::add);
    }

    /**
     * 非线程安全的变更账户余额
     *
     * @param amount 变更金额
     *
     * @return 变更后余额
     */
    public BigDecimal unsafeTrade(BigDecimal amount) {
        this.balance = this.balance.add(amount);
        return this.balance;
    }

}
